/* eslint-disable no-undef */
/* eslint-disable no-unused-vars */
// 引入订单构造集合
import md5 from 'crypto-js/md5'
import Order from '../../dbs/models/order'
import Cart from '../../dbs/models/cart'

module.exports = async (ctx) => {
  // 获取客户端传递过来的参数
  const {
    id,
    price,
    count
  } = ctx.request.body
  // 生成订单号
  const time = Date()
  const orderId = md5(Math.random() * 1000 + time).toString()
  // 判断用户是否已经登陆
  if (!ctx.isAuthenticated()) {
    ctx.body = {
      code: -1,
      msg: 'please login'
    }
  } else {
    const findCart = await Cart.findOne({
      cartNo: id
    })
    const order = new Order({
      id: orderId,
      count,
      total: price * count,
      time,
      user: ctx.session.passport.user,
      name: findCart.detail[0].name,
      imgs: findCart.detail[0].imgs,
      status: 0
    })
    try {
      const result = await order.save()
      if (result) {
        // 创建订单成功，删除购物车的该条数据
        await findCart.remove()
        ctx.body = {
          code: 0,
          id: orderId
        }
      } else {
        ctx.body = {
          code: -1
        }
      }
    } catch (error) {
      ctx.body = {
        code: -1
      }
    }
  }
}
